package com.xyp.a_demo;

/**
 * --- 加油，努力 ---
 *
 * @Author XYP
 * @Date 2024/8/6
 * @Desc 从想做到能做
 */
class Goods {
    public static int isGoods = 0;
    public static int count = 1;
    static Object lock = new Object();
}
class Protector implements Runnable {

    @Override
    public void run() {
        while (true) {
            synchronized (Goods.lock) {
                if (Goods.count > 10) {
                    break;
                } else {
                    if (Goods.isGoods == 1) {
                        try {
                            Goods.lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        System.out.println("生产者生产第" + Goods.count + "件商品...");
                        Goods.isGoods = 1;
                        Goods.lock.notifyAll();
                    }
                }
            }
        }
    }

}
class Consumer implements Runnable {

    @Override
    public void run() {
        while (true) {
            synchronized (Goods.lock) {
                if (Goods.count > 10) {
                    break;
                } else {
                    if (Goods.isGoods == 0) {
                        try {
                            Goods.lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        System.out.println("消费者消费第" + Goods.count + "件商品...");
                        Goods.isGoods = 0;
                        Goods.count++;
                        Goods.lock.notifyAll();
                    }
                }
            }
        }
    }

}

public class Demo3 {
    public static void main(String[] args) {

        new Thread(new Protector()).start();
        new Thread(new Consumer()).start();


    }
}
